RadioMenu = {}
RadioMenuFunc = {}
RadioMenuFunc.__index = RadioMenuFunc
setmetatable(RadioMenu, RadioMenuFunc)

RadioMenuFunc.create = function(self, menu, action, target)
  local l = {}
  setmetatable(l, RadioMenuFunc)
  l.menu = menu
  l.action = action
  l.target = target
  l.menuSelected = -1
  l:setMenuItemExtTable()
  return l
end

RadioMenuFunc.setMenuItemExtTable = function(self)
  local items = self.menu:getChildren()
  for i=0,items:count()-1 do
    local item = items:objectAtIndex(i)
    setObjectExtTable(item, self)
  end
end

RadioMenuFunc.getMenuItemIndex = function(self, node)
  local items = self.menu:getChildren()
  for i=0,items:count()-1 do
    local item = items:objectAtIndex(i)
    item = TypeCast(item, "CCMenuItem")
    if item==node then
      return i
    end
  end
end
RadioMenuFunc.setMenuItemEnabled = function(self, index, enable)
  print("RadioMenuFunc.setMenuItemEnabled", index, enable)
  local items = self.menu:getChildren()
  --TypeCast(items:objectAtIndex(index), "CCMenuItem"):setEnabled(enable)
  setTouchEnabledAll(self.menu, true)
  --TypeCast(self.menu, "CCMenu"):setEnabled(true)
  for i=0,items:count()-1 do
    if index==-1 or i==index then
      TypeCast(items:objectAtIndex(i), "CCMenuItem"):setEnabled(enable)
    end
  end
end
RadioMenuFunc.setMenuState = function(self, index)
  print("RadioMenuFunc.setMenuState", self.menuSelected, index)
  local items = self.menu:getChildren()
  if self.menuSelected>=0 then
    TypeCast(items:objectAtIndex(self.menuSelected), "CCMenuItem"):unselected()
  end
  TypeCast(items:objectAtIndex(index), "CCMenuItem"):selected()

  if self.menuSelected~=index then
    local metaFunc = getmetatable(self.target)
    metaFunc[self.action](self.target, self.menuSelected, index)
    self.menuSelected = index
  end
end

RadioMenuFunc.onSelectMenuItem = function(self, node)
  local index=self:getMenuItemIndex(node)
  self:setMenuState(index)
end
